package com.example.taxiclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class TaxiServiceActivity extends Activity {
	private String ipAddress = "192.168.1.103";
	private String customerId;
	private String customer_longitude;
	private String customer_lattitude;
	private int Status = 0;
	private int longitude;
	private int lattitude;
	private String taxiId;
	private MenuItem item;
	private BMapManager mapmanager;
	private MapView mapview;
	private MyLocationOverlay mlo;
	private MapController mapcontroller;
	private GraphicsOverlay gpo;
	private GeoPoint current;
	private boolean lostgps = true;
	private LocationClient locationclient;
	private SearchLocationListener locationlistener = new SearchLocationListener();
	private DocumentBuilderFactory factory = DocumentBuilderFactory
			.newInstance();
	private DocumentBuilder builder;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		mapmanager = new BMapManager(getApplication());
		mapmanager.init("9CB1FBE0BB605F6FC912BA83E8EAFD40B1B2F99E", null);
		setContentView(R.layout.activity_taxiservice);
		try {
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		locationclient = new LocationClient(getApplicationContext());
		locationclient.registerLocationListener(locationlistener);
		setOption();
		mapview = (MapView) findViewById(R.id.mapview);
		mapview.setBuiltInZoomControls(true);
		mapview.setTraffic(true);
		mlo = new MyLocationOverlay(mapview);
		mapview.getOverlays().add(mlo);
		gpo = new GraphicsOverlay(mapview);
		mapview.getOverlays().add(gpo);
		mapcontroller = mapview.getController();
		locationclient.start();
		locationclient.requestLocation();
		mapcontroller.setZoom(17);

		taxiId = getIntent().getExtras().getString("taxiid");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.taxi, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		if (item.getItemId() == R.id.taking) {
			item.setEnabled(false);
			this.item = item;
			Status = 2;

		} else if (item.getItemId() == R.id.finished) {
			item.setEnabled(false);
			this.item = item;
			Status = 0;

		} else if (item.getItemId() == R.id.off) {
			item.setEnabled(false);
			this.item = item;
			String[] params = { taxiId,
					Integer.toString(current.getLatitudeE6()),
					Integer.toString(current.getLongitudeE6()) };
			UploadTask3 ut3 = new UploadTask3();
			ut3.execute(params);
		}
		return true;
	}

	@Override
	protected void onPause() {
		mapview.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mapview.onResume();
		super.onResume();
	}

	@Override
	protected void onStop() {
		locationclient.stop();
		mapview.destroy();
		super.onStop();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		mapview.onSaveInstanceState(outState);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		mapview.onRestoreInstanceState(savedInstanceState);
		super.onRestoreInstanceState(savedInstanceState);
	}

	private void setOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setCoorType("bd09ll");
		option.setServiceName("com.baidu.location.service_v3.3");
		option.setPoiExtraInfo(false);
		option.disableCache(true);
		option.setScanSpan(5 * LocationClientOption.MIN_SCAN_SPAN);
		option.setPriority(LocationClientOption.GpsFirst);
		locationclient.setLocOption(option);
	}

	private class SearchLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location.getLocType() == 61 || location.getLocType() == 161) {
				current = new GeoPoint(MainActivity.geoTransfer(location
						.getLatitude()), MainActivity.geoTransfer(location
						.getLongitude()));
				LocationData ld = new LocationData();
				ld.latitude = location.getLatitude();
				ld.longitude = location.getLongitude();
				if (location.hasRadius()) {
					ld.accuracy = location.getRadius();
				}
				mlo.setData(ld);
				mapview.refresh();
				mapcontroller.animateTo(current);
				if (location.getLocType() == 61 && lostgps) {
					lostgps = false;
				}
				if (Status == 0) {
					String[] params = { taxiId,
							Integer.toString(current.getLatitudeE6()),
							Integer.toString(current.getLongitudeE6()) };
					UploadTask0 ut0 = new UploadTask0();
					ut0.execute(params);
				} else if (Status == 1) {
					String[] params = { taxiId,
							Integer.toString(current.getLatitudeE6()),
							Integer.toString(current.getLongitudeE6()) };
					UploadTask1 ut1 = new UploadTask1();
					ut1.execute(params);
				} else if (Status == 2) {
					String[] params = { taxiId,
							Integer.toString(current.getLatitudeE6()),
							Integer.toString(current.getLongitudeE6()) };
					UploadTask2 ut2 = new UploadTask2();
					ut2.execute(params);
				}
				return;
			}
			if (!lostgps) {
				Toast.makeText(getApplicationContext(), R.string.lostgpsLabel,
						Toast.LENGTH_SHORT).show();
				lostgps = true;
			}
		}

		@Override
		public void onReceivePoi(BDLocation location) {
		}
	}

	private class UploadTask0 extends AsyncTask<String, Integer, String> {
		private String surl = "http://" + ipAddress
				+ ":8080/taxitest/jaxrs/taxi/waiting/";

		protected String doInBackground(String... params) {
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(url.openStream());
				Node root = doc.getDocumentElement();
				for (Node node = doc.getFirstChild(); node != null; node = node
						.getNextSibling()) {
					if (node.getNodeName().equals("customerId")) {
						Status = 1;
					}

				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
			return null;
		}

	}

	private class UploadTask1 extends AsyncTask<String, Integer, GeoPoint> {
		private String surl = "http://" + ipAddress
				+ ":8080/taxitest/jaxrs/taxi/booked/";

		protected GeoPoint doInBackground(String... params) {
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(url.openStream());
				Node root = doc.getDocumentElement();
				for (Node node = doc.getFirstChild(); node != null; node = node
						.getNextSibling()) {
					if ((node.getNodeName().equals("customerLongitude"))
							&& (node.getNodeName().equals("customerLattitude"))) {
						customer_longitude = node.getNodeValue();
						customer_lattitude = node.getNodeValue();
						Status = 2;
						return new GeoPoint(
								Integer.parseInt(customer_lattitude),
								Integer.parseInt(customer_longitude));
					}

				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(GeoPoint result) {
			gpo.removeAll();
			Symbol symbol = new Symbol();
			Color color = symbol.new Color();
			Geometry gm = new Geometry();
			color.red = 255;
			color.green = 0;
			color.blue = 0;
			gm.setPoint(result, 10);
			color.alpha = 128;
			symbol.setPointSymbol(color);
			Graphic graphic = new Graphic(gm, symbol);
			gpo.setData(graphic);
			mapview.refresh();
			super.onPostExecute(result);
		}

	}

	private class UploadTask2 extends AsyncTask<String, Integer, String> {
		private String surl = "http://" + ipAddress
				+ ":8080/taxitest/jaxrs/taxi/inuse/";

		protected String doInBackground(String... params) {
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(url.openStream());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	private class UploadTask3 extends AsyncTask<String, Integer, String> {
		private String surl = "http://" + ipAddress
				+ ":8080/taxitest/jaxrs/taxi/off/";

		protected String doInBackground(String... params) {
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(url.openStream());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			finish();
			super.onPostExecute(result);
		}

	}

}
